package com.google.code.synchronized_player;

import java.io.IOException;
import java.io.OutputStream;
import java.net.*;
import java.util.LinkedList;
import java.util.Queue;

import android.util.Log;

public class NetSender implements Runnable {
	Socket socketSender;
	SocketAddress socketAddress;
	Queue<Command> commandBuffer = new LinkedList<Command>();

	Thread thread;

	public NetSender(int port, String IP) throws UnknownHostException,
			IOException {
		socketSender = new Socket();
		socketAddress = new InetSocketAddress(InetAddress.getByName(IP), port);
		thread = new Thread(this);
		thread.setDaemon(true);

		thread.start();
	}

	public void Enqueue(Command c) {
		synchronized (commandBuffer) {
			commandBuffer.add(c);
			commandBuffer.notify();
		}
	}

	public void run() {
		while (true) {
			Command c = null;
			synchronized (commandBuffer) {
				while ((c = commandBuffer.poll()) == null) {
					try {
						commandBuffer.wait();
					} catch (InterruptedException e) {
						return;
					}
				}
			}
			
			Send(c);
		}
	}

	private void Send(Command c) {
		try {
			Log.d("Sender", c.getName());
			socketSender = new Socket();
			socketSender.connect(socketAddress);

			OutputStream str = socketSender.getOutputStream();
			byte[] lenbuf = new byte[1];

			byte[] buff = c.getBytes();
			lenbuf[0] = (byte) (buff.length);

			str.write(lenbuf);
			str.write(buff);
			str.flush();
			socketSender.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
